package com.achieve.mqtt.config;

import com.achieve.mqtt.domain.MqttConfigProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

@Configuration
public class MqttOutboundConfig {
    @Autowired
    private MqttConfigProperties mqttConfigProperties;
    @Autowired
    private MqttPahoClientFactory mqttClientFactory;

    // 定义消息通道(发布消息)
    @Bean
    public MessageChannel messageOutboundChannel() {
        return new DirectChannel();
    }

    @Bean
    @ServiceActivator(inputChannel = "messageOutboundChannel")
    public MessageHandler mqttOutboundMessageHandler() {
        MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(
                mqttConfigProperties.getUrl(),
                mqttConfigProperties.getPubClientId(),
                mqttClientFactory);
        messageHandler.setAsync(true);
        messageHandler.setDefaultTopic("default");
        messageHandler.setDefaultQos(0);
        return messageHandler;
    }
}
